package com.group3.customer.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group3.customer.service.IUserService;
import com.group3.customer.service.impl.UserServiceImpl;
import com.group3.customer.util.JsonUtil;
import com.group3.customer.util.SenderUtil;
import com.group3.entity.Customer;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	IUserService service = new UserServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Customer customer = login(request, response);
		Map<String, Object> map = new HashMap<>();
		if (customer != null) {
			map.put("user", customer);
			
		}else {
			map.put("status", "404");
			
		}
		SenderUtil.send(map, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Customer customer = login(request, response);

		Map<String, Object> map = new HashMap<>();
		if (customer != null) {
			HttpSession session=request.getSession();
			session.setAttribute("loginToken", customer);
			map.put("user", customer);
			
		}else {
			map.put("reason", "username or password wrong,login fail!");
			
		}
		
		SenderUtil.send(map, response);
	}

	private Customer login(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		boolean flag = false;
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		Customer uCustomer = new Customer(UUID.randomUUID().toString(),
				userName, password);
		Customer result = service.login(userName, password);

		return result;
	}

}
